package com.sjx.boundarycallback.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;

import com.sjx.boundarycallback.R;
import com.sjx.boundarycallback.databinding.ActivityFileDownloadBinding;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;


/**
 * created sjx on 22/05/26
 * 通过AsyncTask来下载远程更新资源包
 */
public class FileDownloadActivity extends AppCompatActivity {

    private ImageView imageView;
    private Button button;
    private ProgressDialog progressDialog;
    private MyAsyncTask asyncTask;
    private ActivityFileDownloadBinding mBinding;

    private final String IMAGE_PATH = "http://desk.fd.zol-img.com.cn/t_s960x600c5/g4/M01/0D/04/Cg-4WVP_npmIY6GRAKcKYPPMR3wAAQ8LgNIuTMApwp4015.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_download);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_file_download);
        imageView = (ImageView) findViewById(R.id.image_resource);
        button = (Button) findViewById(R.id.btn_download);

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示信息");
        progressDialog.setMessage("正在下载...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);

        button.setOnClickListener(v -> {
            asyncTask = new MyAsyncTask();
            asyncTask.execute(IMAGE_PATH);
        });

    }

    private class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {


        /**
         * 该方法将在执行后台耗时操作前被调用。通常该方法用于完成一些初始化的准备工作，比如在界面上显示进
         * 度条等。
         */
        @Override
        protected void onPreExecute() {
            progressDialog.show();
        }

        /**
         * 重写该方法就是为了执行异步耗时任务（后台线程）,
         * 该方法可以使用publishProgress(Progress... values)方法
         * 更新任务的执行进度
         *
         * @param params
         * @return
         */
        @Override
        protected Bitmap doInBackground(String... params) {
            InputStream inputStream = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Bitmap bitmap = null;
            try {
                URL url = new URL(params[0]);
                URLConnection conn = url.openConnection();
                // 建立链接
                conn.connect();
                // 获取输入流
                inputStream = conn.getInputStream();
                // 获取文件流大小，用于更新进度
                long file_length = conn.getContentLength();
                int len;
                int total_length = 0;
                byte[] data = new byte[1024];
                while ((len = inputStream.read(data)) != -1) {
                    total_length += len;
                    int value = (int) ((total_length / (float) file_length) * 100);
                    // 调用update函数，更新进度
                    publishProgress(value);
//                    data中的0-len数据直接写入outputStream流
                    outputStream.write(data, 0, len);
                }
                byte[] result = outputStream.toByteArray();
                bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return bitmap;
        }

        /**
         * 在 doInBackGround() 方法中调用 publichProgress() 方法更新任务的执行进度后，将会
         * 触发该方法。
         *
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            progressDialog.setProgress(values[0]);
        }

        /**
         * 当 doInBackground() 完成后，系统会自动调用该方法，并将 doInBackground() 方法的返回值传
         * 给该方法。
         *
         * @param bitmap
         */
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            progressDialog.dismiss();
            imageView.setImageBitmap(bitmap);
        }

    }
}